package com.zillion.web.controller.tool;

import com.alibaba.fastjson2.JSONObject;
import com.zillion.certificate.domain.HealthCertificate;
import com.zillion.certificate.service.IExamCertificateService;
import com.zillion.common.annotation.Anonymous;
import com.zillion.common.core.controller.BaseController;
import com.zillion.common.core.domain.AjaxResult;
import com.zillion.common.exception.GlobalException;
import com.zillion.common.utils.http.HttpUtils;
import com.zillion.health.domain.HealthEmployeeReserve;
import com.zillion.health.service.IHealthEmployeeReserveService;
import com.zillion.system.domain.HealthHoliday;
import com.zillion.system.service.IHealthHolidayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 供外部调用的接口
 */
@RestController
@RequestMapping("/out")
public class OutApplyController extends BaseController {

    @Autowired
    private IHealthEmployeeReserveService healthEmployeeReserveService;

    @Autowired
    private IExamCertificateService examCertificateService;

    @Autowired
    private IHealthHolidayService healthHolidayService;

    /**
     * 同步体检结果
     *
     * @param healthEmployeeReserve 体检预约信息
     * @return 结果
     */
    @PostMapping("/updateTjStatus")
    public AjaxResult updateTjStatus(@RequestBody HealthEmployeeReserve healthEmployeeReserve) {
        int i = healthEmployeeReserveService.syncTjStatus(healthEmployeeReserve);
        if (i > 0) {
            return success("体检状态更新成功!");
        } else {
            return error("体检状态更新失败!");
        }
    }

    /**
     * 新增体检健康证信息
     *
     * @param healthCertificate 体检健康证
     * @return 结果
     */
    @PostMapping("/addExamInfo")
    public AjaxResult add(@RequestBody HealthCertificate healthCertificate) {
        if (healthCertificate.getAvatar().isEmpty()) {
            return error("未检测到上传的头像");
        } else if (healthCertificate.getTjResult().isEmpty()) {
            return error("未检测到体检结果");
        } else if (healthCertificate.getIdCard().isEmpty()) {
            return error("未检测到身份证信息");
        } else if (healthCertificate.getReserveDate() == null) {
            return error("未检测到预约时间");
        } else if (healthCertificate.getRegDate() == null) {
            return error("未检测到体检时间");
        }
        AjaxResult res = examCertificateService.insertExamCertificate(healthCertificate);
        return res;
    }

    @Anonymous
    @GetMapping("/getStatutoryHoliday")
    public AjaxResult getStatutoryHoliday() {
        System.out.println("开始更新法定节假日数据--");
        String url = "http://timor.tech/api/holiday/year";
        String sendResult = HttpUtils.sendGet(url);
        JSONObject response = JSONObject.parseObject(sendResult);
        if ("0".equals(response.getString("code"))) {
            JSONObject holidayObject = response.getJSONObject("holiday");
            // 遍历所有节假日
            Set<Map.Entry<String, Object>> entries = holidayObject.entrySet();
            for (Map.Entry<String, Object> entry : entries) {
                JSONObject holidayItem = (JSONObject) entry.getValue();

                // 获取节假日名称
                String holidayName = holidayItem.getString("name");
                // 是否为法定节假日
                String isHoliday = holidayItem.getString("holiday");

                // 获取日期并提取年份
                String date = holidayItem.getString("date");
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                Date parsedDate = null;
                try {
                    parsedDate = formatter.parse(date);
                    // 可以继续使用 parsedDate 进行后续操作
                } catch (ParseException e) {
                    throw new GlobalException("日期转换错误！");
                }
                String year = date.substring(0, 4); // 提取前4位作为年份

                HealthHoliday holiday = new HealthHoliday();
                holiday.setYear(year);
                holiday.setHolidayName(holidayName);
                holiday.setIsHoliday(Boolean.parseBoolean(isHoliday) ? 1 : 0);
                holiday.setHolidayDate(parsedDate);
                // 查询是否存在
                List<HealthHoliday> healthHolidays = healthHolidayService.selectHealthHolidayList(holiday);
                if (healthHolidays.size() > 0) {
                    System.out.println(year + "年节假日及调班数据已存在,无需更新！");
                    return success(); // 如果已存在，则直接退出当前方法
                }
                int inserted = healthHolidayService.insertHealthHoliday(holiday);
                if (inserted > 0) {
                    System.out.println("插入法定节假日数据成功！年份: " + year + ", 日期：" + date + ", 节假日名称: " + holidayName + ", 是否为节假日：" + isHoliday);
                } else {
                    System.out.println("插入法定节假日数据失败！");
                }
            }
        }
        System.out.println("--更新法定节假日数据结束");
        return success();
    }
}
